# pdf+img
from django.http import JsonResponse
from web.models import pdf_grade, pdf_to_img_path, pdf_files_path
from django import forms
from django.forms.models import model_to_dict
from web.apis import result


# ============ 通用工具函数 ============

def model_to_dict_json(model):
    """转换模型表中的一些无法被JSON化的字段"""
    data = model_to_dict(model)
    if 'create_time' in data:
        data['create_time'] = model.create_time.strftime('%Y-%m-%d %H:%M:%S')
    if 'grade' in data:
        data['grade'] = [model_to_dict_json(grade) for grade in data['grade']]
    return data

def handle_file_urls(instance):
    """处理文件URL"""
    data = model_to_dict_json(instance)
    if hasattr(instance, 'pdf_file'):
        data['pdf_file'] = instance.pdf_file.url
    if hasattr(instance, 'pdf_cover'):
        data['pdf_cover'] = instance.pdf_cover.url if instance.pdf_cover else ''
    return data

def check_request_method(allowed_method):
    """请求方法装饰器"""
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            if request.method != allowed_method:
                return JsonResponse(result.result(1, '请求方法错误'))
            return func(request, *args, **kwargs)
        return wrapper
    return decorator


# ============ Form类定义 ============

class pdf_grade_forms(forms.ModelForm):
    class Meta:
        model = pdf_grade
        fields = ['name']

class pdf_files_path_forms(forms.ModelForm):
    class Meta:
        model = pdf_files_path
        fields = ['name', 'pdf_file', 'grade']


# ============ pdf_grade 相关API ============

@check_request_method('POST')
def create_grade(request):
    grade_forms = pdf_grade_forms(request.POST)
    if grade_forms.is_valid():
        grade_forms.save()
        return JsonResponse(result.result(0, '创建成功', model_to_dict(grade_forms.instance)))
    return JsonResponse(result.result(1, '创建失败', result.Forms_GetError(grade_forms)))

@check_request_method('POST')
def delete_grade(request):
    try:
        grade = pdf_grade.objects.get(id=request.POST.get('id'))
        grade.delete()
        return JsonResponse(result.result(0, '删除成功'))
    except pdf_grade.DoesNotExist:
        return JsonResponse(result.result(1, '等级不存在'))

@check_request_method('POST')
def update_grade(request):
    try:
        grade = pdf_grade.objects.get(id=request.POST.get('id'))
        grade_forms = pdf_grade_forms(request.POST, instance=grade)
        if grade_forms.is_valid():
            grade_forms.save()
            return JsonResponse(result.result(0, '修改成功', model_to_dict(grade_forms.instance)))
        return JsonResponse(result.result(1, '修改失败', result.Forms_GetError(grade_forms)))
    except pdf_grade.DoesNotExist:
        return JsonResponse(result.result(1, '等级不存在'))

@check_request_method('GET')
def get_grade(request):
    try:
        grade = pdf_grade.objects.get(id=request.GET.get('id'))
        return JsonResponse(result.result(0, '获取成功', model_to_dict(grade)))
    except pdf_grade.DoesNotExist:
        return JsonResponse(result.result(1, '等级不存在'))

@check_request_method('GET')
def get_grade_list(request):
    grades = pdf_grade.objects.all().order_by('-create_time')
    grade_list = [model_to_dict(grade) for grade in grades]
    return JsonResponse(result.result(0, '获取成功', grade_list))


# ============ pdf_files_path 相关API ============

@check_request_method('POST')
def create_pdf_files_path(request):
    pdf_file = pdf_files_path_forms(request.POST, request.FILES)
    if pdf_file.is_valid():
        instance = pdf_file.save()
        return JsonResponse(result.result(0, '创建成功', handle_file_urls(instance)))
    return JsonResponse(result.result(1, '创建失败', result.Forms_GetError(pdf_file)))

@check_request_method('POST')
def delete_pdf_files_path(request):
    try:
        pdf_file = pdf_files_path.objects.get(pdf_id=request.POST.get('pdf_id'))
        if pdf_file.pdf_file:
            pdf_file.pdf_file.delete()
        if pdf_file.pdf_cover:
            pdf_file.pdf_cover.delete()
        pdf_file.delete()
        return JsonResponse(result.result(0, '删除成功'))
    except pdf_files_path.DoesNotExist:
        return JsonResponse(result.result(1, 'PDF文件不存在'))

@check_request_method('GET')
def get_pdf_files_path(request):
    try:
        pdf_file = pdf_files_path.objects.get(pdf_id=request.GET.get('pdf_id'))
        return JsonResponse(result.result(0, '获取成功', handle_file_urls(pdf_file)))
    except pdf_files_path.DoesNotExist:
        return JsonResponse(result.result(1, 'PDF文件不存在'))

@check_request_method('GET')
def get_pdf_files_path_list(request):
    query = pdf_files_path.objects.all()
    if grade_id := request.GET.get('grade_id'):
        query = query.filter(grade=grade_id)
    pdf_files = query.order_by('-create_time')
    pdf_list = [handle_file_urls(pdf_file) for pdf_file in pdf_files]
    return JsonResponse(result.result(0, '获取成功', pdf_list))
